package com.xx.service.impl;

import com.xx.dto.OrderItemDTO;
import com.xx.entity.PurchaseOrderDetails;
import com.xx.entity.PurchaseOrders;
import com.xx.entity.PurchaseOrders;
import com.xx.mapper.PurchaseOrdersMapper;
import com.xx.service.IProductsService;
import com.xx.service.IPurchaseordersService;
import com.xx.util.OrderIdGenerator;
import com.xx.vo.ProductsDisplayVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class PurchaseordersServiceImpl implements IPurchaseordersService {

    @Autowired
     IProductsService productsService;
    @Autowired
    PurchaseOrdersMapper purchaseOrdersMapper;

    @Override
    public void createOrder(List<OrderItemDTO> orderItemDTOS) {
        PurchaseOrders purchaseorders = new PurchaseOrders();
        //订单编号
        purchaseorders.setOrderId(OrderIdGenerator.generateOrderId());

        //订单日期
        purchaseorders.setOrderDate(new Date());

        //订单状态
        purchaseorders.setStatus(0);

        //        总金额
        List<Integer> collect = orderItemDTOS.stream().map(OrderItemDTO::getProductsId).collect(Collectors.toList());//先拿出所有的商品id
        List<ProductsDisplayVO> listByProductId = productsService.getListByProductId(collect);

        Map<Integer, Integer> map = orderItemDTOS.stream().
                collect(
                        Collectors.toMap(
                                OrderItemDTO::getProductsId,
                                OrderItemDTO::getQuantity)
                );
        //合成订单详情的商品项
        List<PurchaseOrderDetails> purchaseOrderDetails = listByProductId.stream().filter(
                item -> map.containsKey(item.getProductId())).map(
                item -> new PurchaseOrderDetails(
                        purchaseorders.getOrderId(),
                        item.getProductId(),
                        map.get(item.getProductId()),
                        item.getPurchasePrice().doubleValue(),
                        item.getSupplierId(),
                        map.get(item.getProductId())*item.getPurchasePrice().doubleValue()
                )
        ).collect(Collectors.toList());

        //聚合商品项中的价格
        //使用Java 8的流（stream）API计算总价
        double totalAmount = purchaseOrderDetails.stream().
                mapToDouble(PurchaseOrderDetails::getSubtotal).sum();
        //订单总金额
        purchaseorders.setTotalAmount(totalAmount);
        List<PurchaseOrders> purchaseOrdersList = new ArrayList<>();
        purchaseOrdersList.add(purchaseorders);
        int i = purchaseOrdersMapper.insertBatch(purchaseOrdersList);
        System.out.println(i);
    }
}
